package com.moyu.oasys.chat.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyu.common.core.constants.RabbitMQConstants;
import com.moyu.oasys.chat.entity.Message;
import com.moyu.oasys.chat.repository.MessageRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @Author 赵彦博
 * @Date 2024/12/4 13:45
 */
@Component
@Slf4j
public class ChatMessagePublisher {

    private final MessageRepository messageRepository;
    private final RabbitTemplate rabbitTemplate;
    private final ObjectMapper objectMapper;

    public ChatMessagePublisher(MessageRepository messageRepository, RabbitTemplate rabbitTemplate, ObjectMapper objectMapper) {
        this.messageRepository = messageRepository;
        this.rabbitTemplate = rabbitTemplate;
        this.objectMapper = objectMapper;
    }

    public void publish(Map<String, Object> attributes, Message.Type type, String content) {
        Message message = Message.builder()
                .type(type)
                .content(content)
                .username((String) attributes.get("username"))
                .fullName((String) attributes.get("fullName"))
                .profilePicture((String) attributes.get("profilePicture"))
                .createTime(LocalDateTime.now())
                .build();
        if (message.getType() != Message.Type.SYSTEM) {
            messageRepository.save(message);
        }
        try {
            String messageString = objectMapper.writeValueAsString(message);
            rabbitTemplate.convertAndSend(RabbitMQConstants.OASYS_WORK_EXCHANGE, RabbitMQConstants.OASYS_WORK_KEY, messageString);
        } catch (JsonProcessingException e) {
            log.error("Json process error", e);
        }
    }

}
